package qr.server.admin;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;

import qr.core.Game;
import qr.core.Player;

@SuppressWarnings("serial")
public class ManageLeaderboardScreen extends ApplicationScreen {
	
	private Game game;
	private DefaultListModel playersModel = new DefaultListModel();
	
	private JPanel attributes;
	private JPanel actions;
	
	private JLabel name;
	private JList players;
	
	private JButton back;
	
	public ManageLeaderboardScreen(ApplicationWindow parent) {
		super(parent);
		
		this.setLayout(new BorderLayout());
		
		// Create panels
		this.attributes = new JPanel(new FlowLayout());
		this.actions = new JPanel(new FlowLayout());
		
		// Create components
		this.name = new JLabel();
		this.players = new JList();
		this.players.setModel(playersModel);
		this.back = new JButton("Back");
		
		// Place components
		this.attributes.add(new JLabel("Game: "));
		this.attributes.add(this.name);
		this.actions.add(this.back);
		
		this.add(this.attributes, BorderLayout.NORTH);
		this.add(this.players, BorderLayout.CENTER);
		this.add(this.actions, BorderLayout.SOUTH);

		this.back.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				backClicked(e);
			}
		});
	}
	
	public ManageLeaderboardScreen(ApplicationWindow parent, Object[] objs) {
		this(parent);
		if(objs.length == 1 && objs[0] instanceof Game) {
			this.game = (Game) objs[0];
			this.name.setText(game.getGameName());
			List<Player> players = game.getLeaderboard().getPlayers();
			for(Player p : players) {
				playersModel.addElement(p);
			}
		} else {
			System.err.println("ManageLeaderboardScreen: Did not receive Game object, so no leaderboard " +
					"could be displayed. Returning to Home Screen.");
			switchTo("HomeScreen");
		}
	}

	/**
	 * Handler for click event of the back button.
	 * 
	 * @param e Event object
	 */
	private void backClicked(ActionEvent e) {
		switchTo("CreateGameScreen", new Object[]{game});
	}
}
